package com.frogs.ucenter.v1.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.TagStatusEnum;
import com.frogs.system.util.UserInfoCompleteStatusEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
//import com.frogs.ucenter.component.MailingHelper;
import com.frogs.ucenter.dao.TagBaseInfoDao;
import com.frogs.ucenter.dao.TagUserRelationDao;
import com.frogs.ucenter.dao.TagUserRelationTemporaryDao;
import com.frogs.ucenter.dao.UserAccountInfoDao;
import com.frogs.ucenter.dao.UserBaseInfoDao;
import com.frogs.ucenter.dao.UserBaseInfoTemporaryDao;
import com.frogs.ucenter.dao.UserShippingAddressDao;
import com.frogs.ucenter.dao.UserTaskRecordDao;
import com.frogs.ucenter.entity.TagBaseInfo;
import com.frogs.ucenter.entity.TagUserRelation;
import com.frogs.ucenter.entity.TagUserRelationTemporary;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.entity.UserBaseInfo;
import com.frogs.ucenter.entity.UserBaseInfoTemporary;
import com.frogs.ucenter.entity.UserShippingAddressWithAreaCode;
import com.frogs.ucenter.entity.UserTaskRecord;
import com.frogs.ucenter.v1.request.FollowedBaseInfoMergeRequest;
import com.frogs.ucenter.v1.request.FollowedTagAddRequest;
import com.frogs.ucenter.v1.request.FollowedTagDeleteRequest;
import com.frogs.ucenter.v1.request.FollowedTagEditRequest;
import com.frogs.ucenter.v1.request.UserBaseInfoMergeRequest;
import com.frogs.ucenter.v1.request.UserBaseInfoQueryRequest;
import com.frogs.ucenter.v1.request.UserInfoCheckRequest;
import com.frogs.ucenter.v1.request.UserTagAddRequest;
import com.frogs.ucenter.v1.request.UserTagDeleteRequest;
import com.frogs.ucenter.v1.request.UserTagEditRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.DefaultResponse;
import com.frogs.ucenter.v1.response.ShowResponse;
import com.frogs.ucenter.v1.response.UpdateResponse;
import com.frogs.ucenter.v1.service.UserBaseInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@Service(ApiConstants.VERSION + "userBaseInfoService")
public class UserBaseInfoServiceImpl extends UserBaseServiceImpl implements
		UserBaseInfoService {

	private static final Logger log = LoggerFactory.getLogger(UserBaseInfoServiceImpl.class);

	@Resource
	private UserBaseInfoDao userBaseInfoDao;
	@Resource
	private UserBaseInfoTemporaryDao userBaseInfoTemporaryDao;
	
	@Resource
	private UserAccountInfoDao userAccountInfoDao;
	
	@Resource
	private UserShippingAddressDao addressDao;
	
	@Resource
	private UserTaskRecordDao taskRecordDao;

	@Resource
	private TagUserRelationDao tagUserDao;
	@Resource
	private TagUserRelationTemporaryDao tagUserRelationTemporaryDao;

	@Resource
	private TagBaseInfoDao tagDao;
	
//	@Resource
//	private MailingHelper mailingHelper;

	/**
	 * 保存用户基本信息,根据传过来的值判断是否存在id，若存在id，更新相应信息，否则做插入操作
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Response mergeUserBean(Request request) throws Exception {
		try {
			UserBaseInfoMergeRequest ubiar = (UserBaseInfoMergeRequest)request;
			
			String tagIds = ubiar.getTagIds();
			boolean isNew = true;
			List<String> idList = new ArrayList<String>();
			String[] ids = {};
			if(!StringUtil.isEmpty(tagIds)) {
				ids = tagIds.split(",");
				idList = Arrays.asList(ids);
			}
			
			int userId = ubiar.getId();
			List<TagUserRelation> tagUsers = new ArrayList<TagUserRelation>();
			
			UserBaseInfo userBase = userBaseInfoDao.selectById(userId);
			if(null == userBase) {
				userBase = new UserBaseInfo();
				isNew = true;
			} else {
				isNew = false;
			}
			
			fillUserBaseInfo(request, userBase);
			
			if(isNew) {
				userBaseInfoDao.insert(userBase);
				for(int i = 0;i<ids.length; i++){
					TagUserRelation tagUser = new TagUserRelation();
					tagUser.setCreateTime(userBaseInfoDao.getCurrentTime());
					tagUser.setTagId(Integer.parseInt(ids[i]));
					tagUser.setUserId(userBase.getId());
					tagUsers.add(tagUser);
				}
				if(tagUsers.size() > 0) {
					tagUserDao.batchInsert(tagUsers);
				}
				
				//检查是否信息完善
				/*if(checkUserInfoComplete(userId) == 2) {
					log.info("用户id：" + userId + "信息完善，发送邮件");
					sendFillEmail(userId);
				}*/
				
				AddResponse<UserBaseInfo> addresponse = new AddResponse<UserBaseInfo>(); 
				addresponse.setInfo(userBase);
				return addresponse;
			} else {
				Map<String,Object> trParams = new HashMap<String,Object>();
				trParams.put("eqUserId", userId);
				trParams.put("aliasName","tur");
				List<Map<String,Object>> tags = tagUserDao.listUserTags(trParams);
				
				userBase.setId(userId);
				userBaseInfoDao.update(userBase);
				//处理用户标签
				if(idList.size() > 0) {
					Map<String,Object> updateMap = filterTags(tags,idList);
					
					Map<String,Object> params = new HashMap<String,Object>();
					if(updateMap.containsKey("insertList")) {
						List<String> insertList = (List<String>)updateMap.get("insertList");
						for(int i = 0;i<insertList.size(); i++){
							TagUserRelation tagUser = new TagUserRelation();
							tagUser.setCreateTime(userBaseInfoDao.getCurrentTime());
							tagUser.setTagId(Integer.parseInt(insertList.get(i)));
							tagUser.setUserId(userId);
							tagUsers.add(tagUser);
						}
						tagUserDao.batchInsert(tagUsers);
					}
					if(updateMap.containsKey("delList")) {
						List<String> delList = (List<String>)updateMap.get("delList");
						params.put("inIdList", delList);
						tagUserDao.deleteByMap(params);
					}
				}
				
				//检查是否信息完善
				/*if(checkUserInfoComplete(userId) == 2) {
					log.info("用户id：" + userId + "信息完善，发送邮件");
					sendFillEmail(userId);
				}*/
				
				UpdateResponse<UserBaseInfo> updateResponse = new UpdateResponse<UserBaseInfo>(); 
				updateResponse.setInfo(userBase);
				
				return updateResponse;
			}
			
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
	
	/**
	 * 删除用户操作，暂未开发
	 */
	@Override
	public Response deleteUserBean(Request request) throws Exception {
		return null;
	}

	@Override
	public Response getUserBean(Request request) throws Exception {
		try {
			UserBaseInfoQueryRequest ubiqr = (UserBaseInfoQueryRequest) request;
			ShowResponse<UserBaseInfo> resp = new ShowResponse<UserBaseInfo>();
			resp.setInfo(userBaseInfoDao.selectById(ubiqr.getUid()));
			return resp;
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	private Map<String, Object> filterTags(
			List<Map<String, Object>> sourceTags, List<String> newIds) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<String> delIds = new ArrayList<String>();
		List<String> insertIds = new ArrayList<String>();
		Iterator<String> it = newIds.iterator();
		while(it.hasNext()) {
			String id = it.next();
			if(sourceTags.contains(id)) {
				sourceTags.remove(id);
				it.remove();
			} else {
				insertIds.add(id);
			}
		}
		
		if (!sourceTags.isEmpty()) {
			for (Map<String, Object> tag : sourceTags) {
				delIds.add(String.valueOf(tag.get("tagId")));
			}
		}
		if (!insertIds.isEmpty()) {
			resultMap.put("insertList", insertIds);
		}
		if (!delIds.isEmpty()) {
			resultMap.put("delList", delIds);
		}
		return resultMap;
	}

	@Override
	public Response deleteUserTag(Request request) throws Exception {

		UserTagDeleteRequest utdr = (UserTagDeleteRequest) request;
		Response response = new DefaultResponse();
		int userId = utdr.getUserId();
		int tagId = utdr.getTagId();
		Map<String, Object> params = new HashMap<String, Object>();

		try {
			params.put("eqTagId", tagId);
			params.put("eqUserId", userId);

			tagUserDao.deleteByMap(params);
			syncUserTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}

	@Override
	public Response addUserTag(Request request) throws Exception {

		UserTagAddRequest utdr = (UserTagAddRequest) request;
		Response response = new DefaultResponse();
		int userId = utdr.getUserId();
		int tagId = utdr.getTagId();
		Map<String, Object> params = new HashMap<String, Object>();

		try {
			params.put("eqTagId", tagId);
			params.put("eqUserId", userId);

			PageList<TagUserRelation> tags = tagUserDao.selectByMap(params,
					false);
			if (null != tags && tags.size() != 0) {
				throw new Exception("该用户已存在该标签！");
			}

			TagBaseInfo tagBase = tagDao.selectById(tagId);
			if (null == tagBase
					|| tagBase.getStatus() == TagStatusEnum.TAG_STATUS_DELETED
							.getId()) {
				throw new Exception("该标签不存在或已被删除！");
			}

			relateTagUser(userId, tagId);
			syncUserTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}
	
	@Override
	public Response editUserTag(Request request) throws Exception {
		UserTagEditRequest utdr = (UserTagEditRequest) request;
		Response response = new DefaultResponse();
		int userId = utdr.getUserId();
		String tagList = utdr.getTagList();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			if (StringUtil.isEmpty(tagList)) {
				params.put("eqUserId", userId);
				tagUserDao.deleteByMap(params);
			} else {
				String[] tagIds = tagList.split(",");
				params.put("inIds", tagList);
				params.put("eqStatus", TagStatusEnum.TAG_STATUS_NOT_DELETE.getId());
				int count = tagDao.selectCountByMap(params);
				if (count != tagIds.length) {
					throw new Exception("存在不合法标签！");
				}
				
				params.clear();
				params.put("eqUserId", userId);
				tagUserDao.deleteByMap(params);
				for (String tagId : tagIds) {
					relateTagUser(userId, Integer.valueOf(tagId));
				}
			}
			syncUserTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}

	/**
	 * 将标签信息重组并同步到用户标签信息 若不存在用户记录，新增用户记录
	 * 
	 * @param userId
	 */
	private void syncUserTagsToUserBase(int userId) {
		List<Map<String, Object>> tagLists = listUserTags(userId);
		Map<String, Object> params = new HashMap<String, Object>();
		String tags = JSONObject.toJSONString(arrayToJsonMap(tagLists));

		if (null != userBaseInfoDao.selectById(userId)) {
			params.clear();
			params.put("eqId", userId);
			params.put("tags", tags);
			userBaseInfoDao.updateByMap(params);
		} else {
			UserBaseInfo usbi = new UserBaseInfo();
			usbi.setId(userId);
			usbi.setTags(tags);
			userBaseInfoDao.insert(usbi);
		}
	}
	/**
	 * 将标签信息重组并同步到未知用户标签信息 若不存在用户记录，新增用户记录
	 * 
	 * @param userId
	 */
	private void syncFollowedTagsToUserBase(int userId) {
		List<Map<String, Object>> tagLists = listFollowedTags(userId);
		Map<String, Object> params = new HashMap<String, Object>();
		String tags = JSONObject.toJSONString(arrayToJsonMap(tagLists));
		
		if (null != userBaseInfoTemporaryDao.selectById(userId)) {
			params.clear();
			params.put("eqId", userId);
			params.put("tags", tags);
			userBaseInfoTemporaryDao.updateByMap(params);
		} else {
			UserBaseInfoTemporary usbi = new UserBaseInfoTemporary();
			usbi.setId(userId);
			usbi.setTags(tags);
			userBaseInfoTemporaryDao.insert(usbi);
		}
	}

	private JSONObject arrayToJsonMap(List<Map<String, Object>> list) {
		JSONObject json = new JSONObject();
		for (Map<String, Object> map : list) {
			json.put(String.valueOf(map.get("tagId")), map.get("tagName"));
		}

		return json;
	}
	
	/**
	 * 返回0、未完善，1、完善已发邮件； 2、完善未发邮件
	 * @param userId
	 * @return
	 */
	private int checkUserInfoComplete(Integer userId) {
		UserBaseAccountInfo userBaseAccountInfo = userAccountInfoDao.selectByUserId(userId);
		UserShippingAddressWithAreaCode address = getDefaultAddress(userId);
		//完善生日、绑定邮箱、绑定手机,以完善，判断是否发邮件
		if(null != userBaseAccountInfo.getBirthday() 
				&& !StringUtil.isEmpty(userBaseAccountInfo.getEmail())
				&& userBaseAccountInfo.getIsEmailValid() == 1 
				&& !StringUtil.isEmpty(userBaseAccountInfo.getPhone()) 
				&& userBaseAccountInfo.getIsPhoneValid() == 1
				&& userBaseAccountInfo.getSex() > 0 
				&& null != address) {
			UserTaskRecord taskRecord = taskRecordDao.selectById(userId);
			if(null == taskRecord || taskRecord.getTaskRecord() != UserInfoCompleteStatusEnum.SEND_MAIL.getId()) {
				return UserInfoCompleteStatusEnum.UNSEND_MAIL.getId();
			} else {
				return UserInfoCompleteStatusEnum.SEND_MAIL.getId();
			}
		}
		return UserInfoCompleteStatusEnum.UNFINISH.getId();
	}
	
	private void sendFillEmail(Integer userId) {
		UserBaseAccountInfo userBaseAccountInfo = userAccountInfoDao.selectByUserId(userId);
		UserTaskRecord taskRecord = taskRecordDao.selectById(userId);
		
//		mailingHelper.sendInfoFillEmail(userBaseAccountInfo.getEmail());
		if(taskRecord == null ) {
			taskRecord = new UserTaskRecord();
			taskRecord.setId(userId);
			taskRecord.setTaskRecord(UserInfoCompleteStatusEnum.SEND_MAIL.getId());
			taskRecord.setCreateTime(new Date());
			taskRecordDao.insert(taskRecord);
		} else {
			taskRecord.setTaskRecord(taskRecord.getTaskRecord() +1);
			taskRecordDao.update(taskRecord);
		}
	}

	private void fillUserBaseInfo(Request request, UserBaseInfo userBase) {
		UserBaseInfoMergeRequest ubisr = (UserBaseInfoMergeRequest) request;
		
		if (ubisr.getWeight() >= 0) {
			userBase.setWeight(ubisr.getWeight());
		}
		
		if (ubisr.getHeight() >= 0) {
			userBase.setHeight(ubisr.getHeight());
		}
		
		if (ubisr.getAge() >= 0) {
			userBase.setAge(ubisr.getAge());
		}

		if (ubisr.getSex() > 0) {
			userBase.setSex(ubisr.getSex());
		}

		if (!StringUtil.isEmpty(ubisr.getDefaultAddress())) {
			userBase.setDefaultAddress(ubisr.getDefaultAddress());
		}

		if (!StringUtil.isEmpty(ubisr.getDefaultPhone())) {
			userBase.setDefaultPhone(ubisr.getDefaultPhone());
		}

		if (!StringUtil.isEmpty(ubisr.getEmergencyContactName())) {
			userBase.setEmergencyContactName(ubisr.getEmergencyContactName());
		}

		if (!StringUtil.isEmpty(ubisr.getEmergencyPhone())) {
			userBase.setEmergencyPhone(ubisr.getEmergencyPhone());
		}

		if (!StringUtil.isEmpty(ubisr.getHeadImageUrl())) {
			userBase.setHeadImageUrl(ubisr.getHeadImageUrl());
		}

		if (!StringUtil.isEmpty(ubisr.getIdentityCard())) {
			userBase.setIdentityCard(ubisr.getIdentityCard());
		}

		if (!StringUtil.isEmpty(ubisr.getIdentityVerificationResult())) {
			userBase.setIdentityVerificationResult(ubisr
					.getIdentityVerificationResult());
		}

		if (!StringUtil.isEmpty(ubisr.getMedicalInsuranceInfo())) {
			userBase.setMedicalInsuranceInfo(ubisr.getMedicalInsuranceInfo());
		}

		if (!StringUtil.isEmpty(ubisr.getNickName())) {
			userBase.setNickName(ubisr.getNickName());
		}

		if (!StringUtil.isEmpty(ubisr.getOfflineUserInfo())) {
			userBase.setOfflineUserInfo(ubisr.getOfflineUserInfo());
		}

		if (!StringUtil.isEmpty(ubisr.getOrderPhone())) {
			userBase.setOrderPhone(ubisr.getOrderPhone());
		}

		if (!StringUtil.isEmpty(ubisr.getRealName())) {
			userBase.setRealName(ubisr.getRealName());
		}

		if (!StringUtil.isEmpty(ubisr.getTags())) {
			userBase.setTags(ubisr.getTags());
		}

		if (ubisr.getAge() >= 0) {
			userBase.setAge(ubisr.getAge());
		}
		
		if (null != ubisr.getBirthday()) {
			userBase.setBirthday(ubisr.getBirthday());
		}
		
		if (!StringUtil.isEmpty(ubisr.getDiseaseTags())) {
			userBase.setDiseaseTags(ubisr.getDiseaseTags());
		}
		
	}
	private void fillFollowedBaseInfo(Request request, UserBaseInfoTemporary userBase) {
		FollowedBaseInfoMergeRequest ubisr = (FollowedBaseInfoMergeRequest) request;
		
		if (ubisr.getWeight() >= 0) {
			userBase.setWeight(ubisr.getWeight());
		}
		
		if (ubisr.getHeight() >= 0) {
			userBase.setHeight(ubisr.getHeight());
		}
		
		if (ubisr.getSex() > 0) {
			userBase.setSex(ubisr.getSex());
		}
		
		if (ubisr.getAge() > 0) {
			userBase.setAge(ubisr.getAge());
		}
		
		if (null != ubisr.getBirthday()) {
			userBase.setBirthday(ubisr.getBirthday());
		}
		
		if (!StringUtil.isEmpty(ubisr.getDiseaseTags())) {
			userBase.setDiseaseTags(ubisr.getDiseaseTags());
		}
		
		if (!StringUtil.isEmpty(ubisr.getUserId())) {
			userBase.setUserId(ubisr.getUserId());
		}
		
		if (!StringUtil.isEmpty(ubisr.getPhone())) {
			userBase.setPhone(ubisr.getPhone());
		}
		
		if (!StringUtil.isEmpty(ubisr.getRelatives())) {
			userBase.setRelatives(ubisr.getRelatives());
		}
		
		if (!StringUtil.isEmpty(ubisr.getRealName())) {
			userBase.setRealName(ubisr.getRealName());
		}
		
		if (!StringUtil.isEmpty(ubisr.getIdentityCard())) {
			userBase.setIdentityCard(ubisr.getIdentityCard());
		}
		
	}

	@Override
	public Response checkUserInfo(Request request) throws Exception {
		UserInfoCheckRequest checkRequest = (UserInfoCheckRequest)request;
		ShowResponse showResponse = new ShowResponse();
		try{
			Integer userId = checkRequest.getUserId();
			int status = checkUserInfoComplete(userId);
			if( status == UserInfoCompleteStatusEnum.UNSEND_MAIL.getId()) {
				log.info("用户id：" + userId + "信息完善，发送邮件");
				sendFillEmail(userId);
			}
			showResponse.setInfo(status);
			return showResponse;
		} catch(Exception e){
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response mergeFollowedBean(Request request) throws Exception {
		try {
			FollowedBaseInfoMergeRequest ubiar = (FollowedBaseInfoMergeRequest)request;
			boolean isNew = true;
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqUserId", ubiar.getUserId());
			PageList<UserBaseInfoTemporary> userBaseList = userBaseInfoTemporaryDao.selectByMap(params, false);
			UserBaseInfoTemporary userBase = new UserBaseInfoTemporary();
			if(userBaseList.size() == 0) {
				isNew = true;
			} else {
				userBase = userBaseList.get(0);
				isNew = false;
			}
			fillFollowedBaseInfo(request, userBase);
			if(isNew) {
				userBaseInfoTemporaryDao.insert(userBase);
				AddResponse<UserBaseInfoTemporary> addresponse = new AddResponse<UserBaseInfoTemporary>(); 
				addresponse.setInfo(userBase);
				return addresponse;
			} else {
				//userBase.setId(userId);
				userBaseInfoTemporaryDao.update(userBase);
				UpdateResponse<UserBaseInfoTemporary> updateResponse = new UpdateResponse<UserBaseInfoTemporary>(); 
				updateResponse.setInfo(userBase);
				return updateResponse;
			}
		} catch(Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response getFollowedInfo(Request request) throws Exception {
		FollowedBaseInfoMergeRequest followedBaseInfoMergeRequest = (FollowedBaseInfoMergeRequest)request;
		ShowResponse<UserBaseInfoTemporary> showResponse = new ShowResponse<UserBaseInfoTemporary>();
		try{
			Integer userId = followedBaseInfoMergeRequest.getId();
			UserBaseInfoTemporary userBaseInfoTemporary = userBaseInfoTemporaryDao.selectById(userId);
			if(null == userBaseInfoTemporary){
				showResponse.setCode(0);
			}else{
				showResponse.setInfo(userBaseInfoTemporary);
			}
			return showResponse;
		} catch(Exception e){
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	@Override
	public Response deleteFollowedTag(Request request) throws Exception {
		FollowedTagDeleteRequest followedTagDeleteRequest = (FollowedTagDeleteRequest) request;
		Response response = new DefaultResponse();
		int userId = followedTagDeleteRequest.getUserId();
		int tagId = followedTagDeleteRequest.getTagId();
		Map<String, Object> params = new HashMap<String, Object>();

		try {
			params.put("eqTagId", tagId);
			params.put("eqUserId", userId);

			tagUserRelationTemporaryDao.deleteByMap(params);
			syncFollowedTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}

	@Override
	public Response addFollowedTag(Request request) throws Exception {
		FollowedTagAddRequest utdr = (FollowedTagAddRequest) request;
		Response response = new DefaultResponse();
		int userId = utdr.getUserId();
		int tagId = utdr.getTagId();
		Map<String, Object> params = new HashMap<String, Object>();

		try {
			params.put("eqTagId", tagId);
			params.put("eqUserId", userId);

			PageList<TagUserRelationTemporary> tags = tagUserRelationTemporaryDao.selectByMap(params,
					false);
			if (null != tags && tags.size() != 0) {
				throw new Exception("该用户已存在该标签！");
			}

			TagBaseInfo tagBase = tagDao.selectById(tagId);
			if (null == tagBase
					|| tagBase.getStatus() == TagStatusEnum.TAG_STATUS_DELETED
							.getId()) {
				throw new Exception("该标签不存在或已被删除！");
			}

			relateTagFollowed(userId, tagId);
			syncFollowedTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}
	
	@Override
	public Response editFollowedTag(Request request) throws Exception {
		FollowedTagEditRequest utdr = (FollowedTagEditRequest) request;
		Response response = new DefaultResponse();
		int userId = utdr.getUserId();
		String tagList = utdr.getTagList();
		Map<String, Object> params = new HashMap<String, Object>();
		try {
			if (StringUtil.isEmpty(tagList)) {
				params.put("eqUserId", userId);
				tagUserRelationTemporaryDao.deleteByMap(params);
			} else {
				String[] tagIds = tagList.split(",");
				params.put("inIds", tagList);
				params.put("eqStatus", TagStatusEnum.TAG_STATUS_NOT_DELETE);
				int count = tagDao.selectCountByMap(params);
				if (count != tagIds.length) {
					throw new Exception("存在不合法标签！");
				}
				
				params.clear();
				params.put("eqUserId", userId);
				tagUserRelationTemporaryDao.deleteByMap(params);
				for (String tagId : tagIds) {
					relateTagFollowed(userId, Integer.valueOf(tagId));
				}
			}
			syncFollowedTagsToUserBase(userId);
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}

		return response;
	}

}